package com.ding.easycontroller.controller;

import com.ding.easycontroller.model.R;
import com.ding.easycontroller.pojo.ServiceBrief;
import com.ding.easycontroller.pojo.ServiceDetails;
import com.ding.easycontroller.pojo.ServiceUpdateOrAddVO;
import com.ding.easycontroller.service.ServiceService;
import com.ding.easycontroller.work.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/_config/service")
public class _Service {

    @Autowired
    private ServiceService serviceService;


    @PostMapping("/remove")
    public R remove(@RequestParam String id) throws IOException {
        serviceService.removeById(id);
        return R.OK;
    }

    @PostMapping("/updateOrAdd")
    public R updateOrAdd(@Validated ServiceUpdateOrAddVO serviceUpdateOrAddVO) throws IOException {
        Service service = new Service();
        BeanUtils.copyProperties(serviceUpdateOrAddVO, service);
        serviceService.updateOrAdd(service);
        return R.ok(service.getId());
    }

    @GetMapping("/get")
    R get(@RequestParam String id) {
        Service service = serviceService.getById(id);
        if (service == null) {
            return R.NotFound;
        }
        ServiceDetails serviceDetails = new ServiceDetails();
        BeanUtils.copyProperties(service, serviceDetails);
        return R.ok(serviceDetails);
    }


    @GetMapping("/all")
    R all() {
        List<Service> services = serviceService.listAll();
        List<ServiceBrief> serviceBriefs = new ArrayList<>();
        for (Service service : services) {
            ServiceBrief serviceBrief = new ServiceBrief();
            BeanUtils.copyProperties(service, serviceBrief);
            serviceBriefs.add(serviceBrief);
        }
        return R.ok(serviceBriefs);
    }


}

